import json
import re

from django.http import JsonResponse
from django.views import View
from rest_framework.views import APIView

from users_lab.models import Address, Area
from users_lab.views import logger


class AddressView(View):
    """地址数据新增"""
    def post(self, request):
        # 接收参数参数
        user_add = json.loads(request.body.decode())
        title_new = user_add.get('title')  # 地址标题
        receiver_new = user_add.get('receiver')  # 收件人
        province_id_new = user_add.get('province_id')  # 省ｉｄ
        city_id_new = user_add.get('city_id') # 市ｉｄ
        district_id_new = user_add.get('district_id')   # 县ｉｄ
        place_new = user_add.get('place')   # 详细地址
        mobile_new = user_add.get('mobile')  # 手机号
        phone_new = user_add.get('phone')   # 固定电话
        email_new = user_add.get('email')   # 邮箱
        # area1=Area.objects.filter(name=province_id_new)
        # area2=Area.objects.filter(name=city_id_new)
        # area3=Area.objects.filter(name=district_id_new)

        # 校验参数
        if not all([receiver_new, province_id_new, city_id_new, district_id_new, place_new,]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile_new):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if phone_new:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', phone_new):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email_new:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email_new):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        # 保存新增地址
        try:
            address = Address.objects.create(
                title=title_new,
                receiver=receiver_new,
                province_id=province_id_new,
                city_id=city_id_new,
                place=place_new,
                district=district_id_new,
                mobile=mobile_new,
                phone=phone_new,
                email=email_new
            )
        except Exception as e:
            logger.info(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '新增地址失败'})
        # 返回
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0,
                             'errmsg': '新增地址成功',
                             'address': address_dict})

# API: GET /addresses/(?P<pk>\d+)/
class AddressPkView(APIView):
    # 获取指定地址数据
    def get(self, request, pk):
        try:
            add_ress=Address.objects.get(id=pk)
        except Exception as e:
            logger.info(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '获取失败'})
        return JsonResponse({
            "id": add_ress.id,
            "title":add_ress.title,
            "receiver":add_ress.receiver,
            "province":add_ress.province.name,
            "city":add_ress.city.name,
            "district":add_ress.district.name,
            "province_id":add_ress.province_id,
            "city_id":add_ress.city_id,
            "district_id":add_ress.district_id,
            "place":add_ress.place,
            "mobile":add_ress.mobile,
            "phone":add_ress.phone,
            "email":add_ress.email
        })

    def put(self, request, pk):
        # 获取前段数据
        user_add = json.loads(request.body.decode())
        title_new = user_add.get('title')  # 地址标题
        receiver_new = user_add.get('receiver')  # 收件人
        province_id_new = user_add.get('province_id')  # 省ｉｄ
        city_id_new = user_add.get('city_id') # 市ｉｄ
        district_id_new = user_add.get('district_id')   # 县ｉｄ
        place_new = user_add.get('place')   # 详细地址
        mobile_new = user_add.get('mobile')  # 手机号
        phone_new = user_add.get('phone')   # 固定电话
        email_new = user_add.get('email')   # 邮箱

        # 校验参数
        if not all([receiver_new, province_id_new, city_id_new, district_id_new, place_new, ]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile_new):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if phone_new:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', phone_new):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email_new:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email_new):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        try:
            add_user=Address.objects.filter(id=pk).update(
                title=title_new,
                receiver=receiver_new,
                province=province_id_new,
                city=city_id_new,
                district=district_id_new,
                place=place_new,
                mobile=mobile_new,
                phone=phone_new,
                email=email_new
            )
        except Exception as e:
            logger.info(e)
            return JsonResponse({"code":400,
                                 "errmsg":""})
        return JsonResponse({
            "id":add_user,
            "title":title_new,
            "receiver": receiver_new,
            "province":province_id_new,
            "city": city_id_new,
            "district": district_id_new,
            "province_id":province_id_new,
            "city_id": city_id_new,
            "district_id":district_id_new,
            "place":place_new,
            "mobile":mobile_new,
            "phone":phone_new,
            "email":email_new
        })